#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <string.h>
#include "shm_reader.h"
#include "mqtt_handler.h"
#include "msg_queue.h"
#include "json_quick_find.h"
#include "cJSON.h"
#include "sensor_thread.h"

// 全局变量
int running = 1;
MQTTClient mqttClient;
mqd_t msg_queue;
int current_mode = 1; // 1=定时上报 2=对比上报 3=查询上报
cJSON* baseline_data = NULL; // 用于对比上报的基准数据
pthread_mutex_t data_mutex = PTHREAD_MUTEX_INITIALIZER; // 保护基准数据
pthread_mutex_t mode_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mqtt_mutex = PTHREAD_MUTEX_INITIALIZER;
char* shm_ptr = NULL;  // 共享内存指针
int shm_id = -1;      // 共享内存ID


void sig_handler(int sig) {
    if (sig == SIGINT) {
        running = 0;
    }
}

int main() {
    // 初始化消息队列（网关只写）
    msg_queue = create_msg_queue();

    // 初始化共享内存
    init_shm();
    
    // 初始化MQTT
    mqtt_init(&mqttClient, mqtt_callback);
    mqtt_subscribe(mqttClient, "gateway/commands");
    
    // 创建传感器线程
    pthread_t sensor_tid;
    pthread_create(&sensor_tid, NULL, sensor_thread, NULL);
    
    // 主循环
    while(running) {
        pause(); // 简单等待信号
    }
    
    // 清理
    pthread_join(sensor_tid, NULL);
    mqtt_cleanup(mqttClient);

    pthread_mutex_lock(&data_mutex);
    if (baseline_data) {
        cJSON_Delete(baseline_data);
        baseline_data = NULL;
    }
    pthread_mutex_unlock(&data_mutex);
    pthread_mutex_destroy(&data_mutex); 

    close_msg_queue(msg_queue);
    
    return 0;
}